import axios from 'axios';
import router from "@/router/index";
import {sm2, sm4} from 'sm-crypto'


// 创建实例
const service = axios.create({
  // 前缀
  baseURL: import.meta.env.VITE_API_PREFIX,
  method: 'post',
  // 超时
  timeout: 60000,
  // 请求头
  headers: {
    'Content-Type': 'application/json',
  },

});


// 请求拦截器
let loadingInstance;
let timeoutId;

function closeLoading() {
  timeoutId && clearTimeout(timeoutId)
  loadingInstance && loadingInstance.close()
}

service.interceptors.request.use(async config => {
  closeLoading()
  config.headers['X-Token'] = localStorage.getItem("X-Token")
  // 在发送请求之前做些什么
  if (!config.loading === false) {
    timeoutId = setTimeout(() => {
      loadingInstance = ElLoading.service({fullscreen: true})
    }, 500)
  }

  return config;
}, error => {
  closeLoading();
  ElNotification({
    type: 'error',
    duration: 3000,
    title: '请求失败',
    message: error.message
  })
  // 对请求错误做些什么
  return Promise.reject(error);
});
// 添加响应拦截器
service.interceptors.response.use(response => {
  closeLoading();
  if (response.data instanceof Blob) {
    if (response.data.type === 'application/json') return router.push("/login")
    return response.data.data;
  }
  if (response.data.code && response.data.code !== 10000) {
    ElNotification({
      type: 'error',
      duration: 3000,
      title: '请求失败',
      message: response.data.msg
    });
    return Promise.reject(response.data.message);
  }

  return response.data.data
}, error => {
  closeLoading();
  if (error.response.status === 401) return router.push("/login")

  ElNotification({
    type: 'error',
    duration: 3000,
    title: '请求失败',
    message: error
  })

  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error);
});

const post = service.post
const get = service.get
export {service, get, post}